package com.thero.core.net;

import com.thero.core.command.CommandHandler;
import com.thero.core.command.cmd.ClientRegister;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;

/**
 * Created by wusk on 2017/11/27.
 * 接收消息的处理
 */
public class MessageHandler extends SimpleChannelInboundHandler<ProtocolMessage> {

    private static final Logger logger  = LoggerFactory.getLogger(MessageHandler.class);

    private static CommandHandler handler = new CommandHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage message) throws Exception {
        // 收到消息直接打印输出
        System.out.println(ctx.channel().remoteAddress() + " Say : " + message);
        if(message.getHeader().getCommand() == 1000){
            try{
                ClientRegister cmd = new ClientRegister(message);
                handler.register(ctx.channel(), cmd.getHome());
            }catch (Exception e){
                logger.error("", e);
            }
        }else {
            handler.handle(message);
        }

//        Command handler = manager.getCommand(message.getHeader().getCommand());
//        ProtocolMessage response = handler.execute(message);
//
//        if(null != response){
//            // 响应返回给客户端
//            ctx.writeAndFlush(response);
//        }
    }

    /**
     * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
     * channelActive 和 channelInActive 在后面的内容中讲述，这里先不做详细的描述
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");

        ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");

        super.channelActive(ctx);
    }
}
